package helper

import (
	"strings"
	//"strconv"
	"errors"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/buger/jsonparser"
)

//字符串查找 中间字符 截取
func GetBetweenStr(str, start, end string) string {
    n := strings.Index(str, start)
    if n == -1 {
        n = 0
    }
    str = string([]byte(str)[n:])
    m := strings.Index(str, end)
    if m == -1 {
        m = len(str)
    }
    str = string([]byte(str)[:m+1])
    return str
}

func Substr(str string, start, length int) string {
	rs := []rune(str)
	rl := len(rs)
	end := 0
	if start < 0 {
		start = rl - 1 + start
	}
	end = start + length
	if start > end {
		start, end = end, start
	}
	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}
	return string(rs[start:end])
}

func GetJsonField(jsonStr string) ([]string, error) {
	var dat map[string]interface{}
	var keySlice []string
	err := json.Unmarshal([]byte(jsonStr), &dat)
	if err == nil {
        for key, _ := range dat {
			keySlice = append(keySlice, key)
		}
		return keySlice, nil
	}
	return nil, err
}
	
func JsonToDataRangeStr(jsonStr string,uid int64)([]int64, []string, bool, error){
    type StoreRange struct {
		UserId   int64   `json:"user_id"` 
		StoreIds []int64 `json:"store_ids"`
	}
	type AppRange struct {
		UserId  int64    `json:"user_id"` 
		AppIds  []string `json:"app_ids"`
	}
	dataRange := struct {
		StoreIds    []int64      `json:"store_ids"`
	    AppIds      []string     `json:"app_ids"`
        PartByUser  bool         `json:"part_by_user"` 
		StoreRanges []StoreRange `json:"store_range"`
		AppRanges   []AppRange   `json:"app_range"`
	}{}
	err := json.Unmarshal([]byte(jsonStr), &dataRange)
	if err != nil {
	   beego.Debug("JsonToDataRangeStr error:",jsonStr,err.Error())
       return []int64{}, []string{}, false, err
	}
	beego.Debug("uid,JsonToDataRangeStr:",uid,jsonStr)
	if uid > 0 {
	   for _, v := range dataRange.StoreRanges{
	      if v.UserId == uid {
		     dataRange.StoreIds = v.StoreIds
			 break
		  }
	   }
	   for _, v := range dataRange.AppRanges{
	      if v.UserId == uid {
		     dataRange.AppIds = v.AppIds
			 break
		  }
	   }
	   beego.Debug("uid StoreIds:", uid, dataRange.StoreIds)
	   beego.Debug("uid AppIds:", uid, dataRange.AppIds)
	}
	return dataRange.StoreIds, dataRange.AppIds, dataRange.PartByUser, nil
}

func SplitJsonArr(rawJson string) ([]string, error) {
    var (
	    arrJson     []string = make([]string, 0, 10)
		interResult []byte
	)
	if len(rawJson) < 3 {
	    return arrJson, errors.New("rawJson is invalid")
	}
	jsonparser.ObjectEach([]byte(rawJson), func(key []byte, val []byte, t jsonparser.ValueType, _ int) error {
		interResult = val
		return nil
	})
	if len(interResult) < 3 {
	    return arrJson, errors.New("interResult is invalid")
	}
	jsonparser.ArrayEach(interResult, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
		arrJson = append(arrJson, string(value))
	})
    return arrJson, nil
}
